<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 16/4/11
 * Time: 下午3:19
 * Describe:
 *
 * 用户使用余额, 判断是否可用
 * 余额不足, 未登录, 及其它 合法性判断
 */

namespace liketry\models;

use services\models\MemberInfo;
use Yii;
use services\sms\SmsSend;
use yii\base\Model;

class OrderMemberMoneySmsForm extends Model
{
    public $member_money;
    public $bestry_uid;
    public $cellBind = false;
    public $cellNumber = '';
    public $member_no;
    public $code = null;

    public function rules()
    {
        return [
            [['member_money','bestry_uid'], 'required'],
            ['member_money', 'number'],
            ['bestry_uid', 'validateCustom'],


        ];
    }

    public function validateCustom()
    {

        if (empty($this->bestry_uid) || !is_numeric($this->bestry_uid)) {
            $this->addError('bestry_uid', '用户没有登录');

        }

        $user = \services\models\MemberInfoBestry::find()
            ->joinWith('memberInfo')
            ->where(['uid' => $this->bestry_uid])->one();
        if (empty($user)) {
            $this->addError('bestry_uid', '用户没有登录');
        } else {
            if ($user->member_money < $this->member_money) {
                $this->addError('member_money', '您的余额不足');
            }
            if (!$user->memberInfo->checkCell()) {
                $this->addError('bestry_uid', '请先绑定手机才可使用余额');
                $this->cellBind = false;
            }

            $this->cellBind = true;
            $this->cellNumber = $user->memberInfo->cell;
            $this->member_no = $user->memberInfo->member_no;

        }

    }

    public function sendSms()
    {
        if (!$this->validate()) {
            return false;
        }
        $sms = SmsSend::factory();

        $this->code = MemberInfo::getCellCode($this->cellNumber);

        return $sms->send($this->cellNumber, "您的手机验证码为： " . $this->code . ",请尽快登陆激活", $this->member_no);

    }

    public function attributeLabels()
    {
        return [
            'member_money' => '余额',
            'bestry_uid' => 'bestry UID',
        ];
    }


}